package com.wise.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wise.pojo.MsgConstants;
import com.wise.pojo.MsgLog;
import com.wise.service.IMsgLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @author rzc
 * @date 2021/9/22
 */

@Configuration
@Slf4j
public class RabbitmqConfig {
    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;
    @Autowired
    private IMsgLogService msgLogService;

    @Bean
    public RabbitTemplate createRabbitTemplate(){
        cachingConnectionFactory.setPublisherReturns(true);
        cachingConnectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        rabbitTemplate.setMandatory(true);
        /**
         * 消息确认回调，确认消息是否到达broker
         * data： 消息确认唯一标识
         * ack: 确认结果 布尔值 true消息发送成功   false消息发送失败
         * cause: 失败原因
         */
        rabbitTemplate.setConfirmCallback((data,ack,cause)->{
            String msgId = data.getId();
            if (ack){
                log.info("=============消息发送成功");
                //更新消息状态
                msgLogService.update(new UpdateWrapper<MsgLog>().set("status",1).eq("msgId",msgId));
            }else {
                log.info("=============消息发送失败",msgId);
            }
        });

        /**
         * 消息失败回调，比如router不到queue时回调
         * msg:消息主题
         * repCode:响应码
         * repText:响应描述* exchange:交换机
         * * routingKey:路由键
         * */
        rabbitTemplate.setReturnCallback((msg,repCode,repText,exchange,routingKey)->{
            log.error("{}=======================>消息发送到queue时失败",msg.getBody());
        });
        return rabbitTemplate;
    }


    @Bean        //声明direct交换机
    public DirectExchange directExchange(){
        return new DirectExchange(MsgConstants.MAIL_EXCHANGE_NAME);
    }

    @Bean		//声明队列
    public Queue queue(){
        return new Queue(MsgConstants.MAIL_QUEUE_NAME);
    }

    @Bean		//将队列通过routeKey绑定到交换机上
    public Binding binding(Queue queue, DirectExchange directExchange){
        return BindingBuilder.bind(queue).to(directExchange).with(MsgConstants.MAIL_ROUTING_KEY_NAME);
    }
}
